"""遵循WSGI协议的web框架"""


def index(env):
    return "This is index page."


def env_list(env):
    from io import StringIO

    stdout = StringIO()
    for k, v in env.items():
        print(k, '=', repr(v), file=stdout)
    return stdout.getvalue()


urlpatterns = [
    ('/', index),
    ('/env/list/', env_list),
]


def demo_app(environ, start_response):
    message = 'not found'
    path_info = environ.get('PATH_INFO')
    for url, func in urlpatterns:
        if path_info == url:
            message = func(environ)

    start_response("200 OK", [('Content-Type', 'text/plain; charset=utf-8')])
    return [message.encode('utf-8')]


if __name__ == '__main__':
    from wsgiref.simple_server import make_server

    with make_server('', 8800, demo_app) as httpd:
        sa = httpd.socket.getsockname()
        print("Serving HTTP on", sa[0], "port", sa[1], "...")

        # httpd.handle_request()  # serve one request, then exit
        httpd.serve_forever()  # serve until process is killed

# http://localhost:8800/env/list/
